#!/usr/bin/env python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
from utils.converter import Converter


class HtmlHelper(object):
    '''
    helper methods for html related operation
    '''

    @staticmethod
    def getHtmlString(htmlElement):
        '''
        Get inner string of an element
        '''
        if htmlElement:
            if htmlElement.string:
                return htmlElement.string.strip()
        return None
    
    @staticmethod
    def getTableString(tableElement):
        '''
        Convert table element to a csv format string
        '''
        if tableElement and tableElement.find("tr"):           
           datasets = []
           headings = [HtmlHelper.getHtmlString(th) for th in tableElement.find("tr").find_all("th")]
           datasets.append(headings)
           for row in tableElement.find_all("tr")[1:]:
               dataset = [HtmlHelper.getHtmlString(td) for td in row.find_all("td")]
               datasets.append(dataset)
           return "\r\n".join(" , ".join(map(Converter.xstr, dataRow)) for dataRow in datasets)
        return None

    @staticmethod
    def getFieldValueByLabel(parentElement, label, valueFieldFilter=None):
        '''Get the field value by given label. We assume the label and value elements are on the same level and next to label.
        params:
            parentElement: parent element to search
            label: string or regular expression for the label
            valueFieldFilter: filter to get value field in case it is a a sub level. e.g. the name 'span'
        '''
        if not parentElement:
            return None
        labelElement = parentElement.find(text=label)
        if not labelElement:
            return None
        valueElement = labelElement.parent.find_next_sibling()
        if valueElement and valueFieldFilter:
            valueElement = valueElement.find(valueFieldFilter)
        return HtmlHelper.getHtmlString(valueElement)